package com.shaoyu.elasticsearch.service;

import com.shaoyu.elasticsearch.base.BaseDataType;
import com.shaoyu.elasticsearch.dao.ElasticSearchIndexRepository;
import com.shaoyu.elasticsearch.entity.ElasticsearchIndex;
import com.shaoyu.elasticsearch.util.CommonUtil;
import com.shaoyu.elasticsearch.util.IDUtil;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ElasticSearchIndexServiceImpl implements ElasticSearchIndexService{
    private static Logger logger = LoggerFactory.getLogger(ElasticSearchIndexServiceImpl.class);

    private Client client =  ElasticSearchClientService.getNormalTransportClient();


    @Autowired
    private ElasticSearchIndexRepository indexRepository;

    private List<ElasticsearchIndex> list ;

    private void setList(){
        list =  indexRepository.findAll();
    }

    public  <T extends BaseDataType> boolean createIndex(ElasticsearchIndex index, T document){
        ElasticsearchIndex idx ;
        setList();
        if(!list.contains(index)){
            idx = indexRepository.findElasticsearchIndexByIndexAndType(index.getIndex(),index.getType());
        }else{
            idx = index;
        }
        try{
            byte[]json = CommonUtil.getMapper().writeValueAsBytes(document);
            IndexResponse response = client.prepareIndex(index.getIndex(),index.getType())
                    .setId(IDUtil.getIncrementId()+"")
                    .setSource(json)
                    .get();
            if(response.getResult().getOp()==0){
                logger.info("创建index文档成功!");
                if(idx!=null){
                    indexRepository.save(idx);
                    list.add(indexRepository.findElasticsearchIndexByIndexAndType(index.getIndex(),index.getType()));
                }
            }else{
                logger.error("创建index文档失败!result:"+response.getResult());
                return false;
            }
        }catch (Exception e){
            logger.error("创建index文档出错",e);
            return false;
        }
        return true;
    }

    public GetResponse getDocument(ElasticsearchIndex index,int idx){
        GetResponse response = client.prepareGet(index.getIndex(), index.getType(), idx+"").get();
        return response;
    }
    public DeleteResponse deleteDocument(ElasticsearchIndex index,int idx){
        setList();
        if(!list.contains(index)){
            ElasticsearchIndex i  = indexRepository.findElasticsearchIndexByIndexAndType(index.getIndex(),index.getType());
            if(i==null){
                logger.error("没有找到索引:"+index.getIndex()+"-"+index.getType());
                return null;
            }
            setList();
        }
        DeleteResponse response = client.prepareDelete(index.getIndex(), index.getType(), idx+"").get();
        return response;
    }
}
